package com.qf.service.impl;

import com.qf.dao.CartDao;
import com.qf.dao.CartDaoImpl;
import com.qf.dao.GoodsDao;
import com.qf.dao.GoodsDaoImpl;
import com.qf.pojo.Cart;
import com.qf.pojo.Goods;
import com.qf.service.CartService;

import java.util.List;

/**
 * @author 千锋健哥
 */
public class CartServiceImpl implements CartService {

    @Override
    public void addCart(Cart cart) {
        //1. 根据商品id查询商品对象
        GoodsDao goodsDao = new GoodsDaoImpl();
        Goods goods = goodsDao.findById(cart.getPid());

        //2. 设置购物车中商品对象
        cart.setGoods(goods);

        //3. 计算购物车中的商品小计
        Integer sum = cart.getNum() * goods.getPrice();
        cart.setMoney(sum);

        //4. 调用dao将购物车对象加入到表中
        CartDao cartDao = new CartDaoImpl();
        cartDao.insert(cart);
    }

    @Override
    public List<Cart> findCartByUid(Integer uid) {
        //1. 查询购物车列表
        CartDao cartDao = new CartDaoImpl();
        List<Cart> list = cartDao.findByUid(uid);

        //2. 遍历购物车列表
        GoodsDao goodsDao = new GoodsDaoImpl();
        if (list != null) {
            for (Cart cart : list) {
                //3. 根据商品id, 查询对应的商品对象
                Goods goods = goodsDao.findById(cart.getPid());
                //4. 将商品对象存入购物车列表中
                cart.setGoods(goods);
            }
        }

        return list;
    }

    @Override
    public void deleteByUid(Integer uid) {
        CartDao cartDao = new CartDaoImpl();
        cartDao.deleteByUid(uid);
    }

}
